package org.hepeng.workx.util;

import org.apache.commons.collections.CollectionUtils;
import org.hepeng.workx.mybatis.interceptor.PageList;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author he peng
 */
public class PageQuerys {

    private static final ThreadLocal<PageQuery> PAGE_QUERY_THREAD_LOCAL = ThreadLocal.withInitial(() -> null);

    public static void markQueryPage(Long startPage, Integer pageSize) {
        PAGE_QUERY_THREAD_LOCAL.set(new PageQuery(startPage , pageSize));
    }

    public static void markQueryPage(PageQuery pageQuery) {
        PAGE_QUERY_THREAD_LOCAL.set(pageQuery);
    }

    public static PageQuery getPageQuery() {
        return PAGE_QUERY_THREAD_LOCAL.get();
    }

    public static void clear() {
        PAGE_QUERY_THREAD_LOCAL.remove();
    }

    public static <T> PageResultSet<T> extractPageResultSet(List<T> results) {
        if (PageList.class.isAssignableFrom(results.getClass())) {
            PageList pageList = (PageList) results;
            return pageList.getPageResultSet();
        }
        return null;
    }

    public static <T , R> PageResultSet<R> extractPageResultSet(List<T> results , DataProcess<T , R> dataProcess) {
        PageResultSet<T> pageResultSet = extractPageResultSet(results);
        PageResultSet<R> newPageResultSet = new PageResultSet<>();
        BeanUtils.copyProperties(pageResultSet , newPageResultSet);
        if (Objects.nonNull(pageResultSet) && CollectionUtils.isNotEmpty(pageResultSet.getRecords())) {
            List<R> records = new ArrayList<>();
            pageResultSet.getRecords().stream().forEach(t -> {
                R r = dataProcess.process(t);
                records.add(r);
            });
            newPageResultSet.setRecords(records);
        }
        return newPageResultSet;
    }
}
